package no.nordicsemi.android.dfuupdate;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;

import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class UpdateResultActivity extends AppCompatActivity {

    private HashMap resultMap = new HashMap<String,String>();
    public static String keyWord;
    private UpdateResultAdapter listAdapter;
    TextView count;
    SearchView searchView;
    List<Result> resultList = new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_result);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        resultMap = JSON.parseObject(getIntent().getStringExtra("UPDATE_RESULT"),HashMap.class);
        Iterator iterator = resultMap.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Result result = new Result(String.valueOf(entry.getKey()),String.valueOf(entry.getValue()));
            resultList.add(result);
        }
        listAdapter = new UpdateResultAdapter();
        listAdapter.clearLists();
        setGui();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    void setGui() {
        final Toolbar toolbar = findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        count = (TextView) findViewById(R.id.update_count);

        final ListView listView = (ListView) findViewById(android.R.id.list);
        listView.setEmptyView(findViewById(android.R.id.empty));
        listView.setAdapter(listAdapter);
        listView.setTextFilterEnabled(true);
        searchView = (SearchView) findViewById(R.id.updated_searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d("QUERY" ,"NEWTEXT =" + newText);
                if(!TextUtils.isEmpty(newText)) {
                    keyWord = newText.toUpperCase();
                    Log.d("ListVIEW", "SetFIlterText_" + keyWord);
                    listAdapter.filtList(newText.toUpperCase());
                    count.setText("count : " + listAdapter.getItemCount());

                } else {
                    //listView.clearTextFilter();
                    keyWord = "";
                    listAdapter.filtList("");
                    count.setText("count : " + listAdapter.getItemCount());
                }
                return false;
            }


        });

        listAdapter.update(resultList);
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.export, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                onBackPressed();
                onBackPressed();
                break;
            case R.id.update_result:
                Toast.makeText(this,"export data", Toast.LENGTH_SHORT).show();
                ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("UPDATE_RESULT", genContent());
                clipboard.setPrimaryClip(clip);
                break;

        }
        return true;
    }

    public String genContent() {
        StringBuilder sb = new StringBuilder();
        sb.append("设备名称,MAC地址,升级结果;\r\n");
        for(Result re : resultList) {
            sb.append(re.getDevName()).append(",").append(re.getDevMac()).append(",").append(re.getDevRsult()).append(";\r\n");
        }
        return sb.toString();
    }

    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }

}


